package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/honwee/awm/internal/api/dto"
	"github.com/honwee/awm/internal/service"
	"github.com/honwee/awm/pkg/logger"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

type ProjectUserHandler struct {
	projectUserService *service.ProjectUserService
	log                *zap.SugaredLogger
}

func NewProjectUserHandler(projectUserService *service.ProjectUserService) *ProjectUserHandler {
	return &ProjectUserHandler{
		projectUserService: projectUserService,
		log:                logger.Logger.Sugar(),
	}
}

// GenerateAPIKey godoc
// @Summary 生成API Key
// @Description 为指定的项目和用户生成新的API Key
// @Tags API Key管理
// @Accept json
// @Produce json
// @Param request body dto.GenerateAPIKeyRequest true "生成API Key请求"
// @Success 200 {object} dto.APIKeyResponse
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /api-keys/generate [post]
func (h *ProjectUserHandler) GenerateAPIKey(c *gin.Context) {
	var req dto.GenerateAPIKeyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	apiKey, err := h.projectUserService.GenerateAPIKey(req.ProjectID, req.UserID)
	if err != nil {
		h.log.Errorw("Failed to generate API key",
			"project_id", req.ProjectID,
			"user_id", req.UserID,
			"error", err)
		c.Error(err)
		return
	}

	projectUser, err := h.projectUserService.ValidateAPIKey(apiKey)
	if err != nil {
		h.log.Errorw("Failed to get project user after generating API key",
			"project_id", req.ProjectID,
			"user_id", req.UserID,
			"error", err)
		c.Error(err)
		return
	}

	response := &dto.APIKeyResponse{}
	response.FromModel(projectUser)
	c.JSON(http.StatusOK, response)
}

// DeleteAPIKey godoc
// @Summary 删除API Key
// @Description 删除指定项目和用户的API Key
// @Tags API Key管理
// @Accept json
// @Produce json
// @Param project_id path string true "项目ID"
// @Param user_id path string true "用户ID"
// @Param Authorization header string true "API Key认证，格式：Bearer {API Key}"
// @Security ApiKeyAuth
// @Success 200 {object} map[string]string
// @Failure 400 {object} map[string]string
// @Failure 401 {object} map[string]string "未授权"
// @Failure 500 {object} map[string]string
// @Router /api-keys/{project_id}/{user_id} [delete]
func (h *ProjectUserHandler) DeleteAPIKey(c *gin.Context) {
	projectIDStr := c.Param("project_id")
	if projectIDStr == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "project_id is required"})
		return
	}

	projectID, err := strconv.ParseUint(projectIDStr, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project_id format"})
		return
	}

	userID := c.Param("user_id")
	if userID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "user_id is required"})
		return
	}

	err = h.projectUserService.DeleteAPIKey(projectID, userID)
	if err != nil {
		h.log.Errorw("Failed to delete API key",
			"project_id", projectID,
			"user_id", userID,
			"error", err)
		c.Error(err)
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "API key deleted successfully"})
}

// RegenerateAPIKey godoc
// @Summary 重新生成API Key
// @Description 为指定的项目和用户重新生成API Key
// @Tags API Key管理
// @Accept json
// @Produce json
// @Param project_id path string true "项目ID"
// @Param user_id path string true "用户ID"
// @Param Authorization header string true "API Key认证，格式：Bearer {API Key}"
// @Security ApiKeyAuth
// @Success 200 {object} dto.APIKeyResponse
// @Failure 400 {object} map[string]string
// @Failure 401 {object} map[string]string "未授权"
// @Failure 500 {object} map[string]string
// @Router /api-keys/{project_id}/{user_id}/regenerate [post]
func (h *ProjectUserHandler) RegenerateAPIKey(c *gin.Context) {
	projectIDStr := c.Param("project_id")
	if projectIDStr == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "project_id is required"})
		return
	}

	projectID, err := strconv.ParseUint(projectIDStr, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project_id format"})
		return
	}

	userID := c.Param("user_id")
	if userID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "user_id is required"})
		return
	}

	apiKey, err := h.projectUserService.GenerateAPIKey(projectID, userID)
	if err != nil {
		h.log.Errorw("Failed to regenerate API key",
			"project_id", projectID,
			"user_id", userID,
			"error", err)
		c.Error(err)
		return
	}

	projectUser, err := h.projectUserService.ValidateAPIKey(apiKey)
	if err != nil {
		h.log.Errorw("Failed to get project user after regenerating API key",
			"project_id", projectID,
			"user_id", userID,
			"error", err)
		c.Error(err)
		return
	}

	response := &dto.APIKeyResponse{}
	response.FromModel(projectUser)
	c.JSON(http.StatusOK, response)
}

// CreateProjectUserRequest 创建项目用户关系请求
type CreateProjectUserRequest struct {
	ProjectID uint64 `json:"project_id" binding:"required"`
	UserID    string `json:"user_id" binding:"required"`
	Role      int8   `json:"role" binding:"required,oneof=1 2 3"` // 1: 管理员, 2: 开发者, 3: 访客
}

// CreateProjectUser godoc
// @Summary 创建项目用户关系
// @Description 创建新的项目用户关系
// @Tags 项目用户管理
// @Accept json
// @Produce json
// @Param request body CreateProjectUserRequest true "创建项目用户关系请求"
// @Success 200 {object} map[string]string
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /project-users [post]
func (h *ProjectUserHandler) CreateProjectUser(c *gin.Context) {
	var req CreateProjectUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	err := h.projectUserService.CreateProjectUser(req.ProjectID, req.UserID, req.Role)
	if err != nil {
		h.log.Errorw("Failed to create project user",
			"project_id", req.ProjectID,
			"user_id", req.UserID,
			"role", req.Role,
			"error", err)
		c.Error(err)
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Project user created successfully"})
}
